import Row from "./Row";
import ColGroup from "./ColGroup";
import { forwardRef, useRef } from "react";
import useTableReady from "./useTableReady";
import { useForm } from "../../../framework/common/context/metadata-context";
import { useSubscribe } from "../../../framework/common/eventBus";
import { useUpdate } from "ahooks";
import { fieldFilter, fieldFilterNormal } from "../../../framework/common/utils/filter";

export default forwardRef(function ({ scale, leftFixedTableRef, data, group, children }, ref) {
  return (
    <div ref={ref} className="relative runtime-data-list-wrapper ">
      {children}
      <FixedTable scale={scale} data={data} group={group} leftFixedTableRef={leftFixedTableRef}></FixedTable>
    </div>
  );
});

function FixedTable({ scale, leftFixedTableRef, data, group }) {
  const form = useForm();
  const updater = useUpdate();
  const { isReady } = useTableReady(group.code + ".ready");

  const heightRef = useRef("41px");
  useSubscribe(`group.fiexedTableUpdate.${group.code}`, () => {
    updater();
  });
  useSubscribe("operation.header.update." + group.code, (height) => {
    heightRef.current = height;
    updater();
  });

  if (isReady === false) return null;

  let fixedColumnPc = (group.fixedColumnPc || 0) + (group.loop_table_sid ? 1 : 0);

  let filterFields = group.fields.filter(fieldFilter);

  let normalFilterFields = group.fields.filter(fieldFilterNormal);
  return (
    <div className="absolute top-0 left-0 overflow-hidden bg-white fixed-table-wrapper" style={{ maxHeight: 500 - form.scrollBarWidth + "px", top: heightRef.current }}>
      <table ref={leftFixedTableRef} className="runtime-data-list mainTable fixed-table table-process-form">
        <ColGroup scale={scale} isFromFixedTable={true} fixedColum={fixedColumnPc} isFiexedTable={true} group={group} fields={group.fields}></ColGroup>
        <tbody>
          {data.map((row, index) => (
            <Row filterFields={filterFields} normalFilterFields={normalFilterFields} isFromFixedTable={true} isFiexedTable={true} fixedColum={fixedColumnPc} group={group} groupCode={group.code} rowIndex={index} key={row.__cid__} row={row} fields={group.fields}></Row>
          ))}
        </tbody>
      </table>
    </div>
  );
}
